import Vue from 'vue'
import {getRouters} from '@/api/menu'
import VueRouter from 'vue-router'
import store from '@/store/index'
import NProgress from 'nprogress'
import allIcon from '@/core/icons'
import 'nprogress/nprogress.css' // progress bar style
import MultilevelMenuExample from './modules/multilevel.menu.example'
import BreadcrumbExample from './modules/breadcrumb.example'
import KeepAliveExample from './modules/keep.alive.example'
import ComponentBasicExample from './modules/component.basic.example'
import ComponentExtendExample from './modules/component.extend.example'
import PermissionExample from './modules/permission.example'
import MockExample from './modules/mock.example'
// import VideosExample from './modules/videos.example'
import ExTernalLinkExample from './modules/external.link.example'
// import CooperationExample from './modules/cooperation.example'
import systemPost from './modules/system.post'

Vue.use(VueRouter)

import Layout from '@/layout'
import EmptyLayout from '@/layout/empty'
import {isRelogin} from "@/util/request";
import {Message} from "element-ui";

export const constantRoutes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/system/user/login'),
        meta: {
            title: '登录'
        }
    },
    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [
            {
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/index'),
                meta: {
                    title: store.state.settings.dashboardTitle
                }
            },
            {
                path: 'personal',
                component: EmptyLayout,
                redirect: '/personal/setting',
                meta: {
                    title: '个人中心',
                    breadcrumb: false
                },
                children: [
                    {
                        path: 'setting',
                        name: 'personalSetting',
                        component: () => import('@/views/personal/setting'),
                        meta: {
                            title: '个人设置'
                        }
                    },
                    {
                        path: 'edit/password',
                        name: 'personalEditPassword',
                        component: () => import('@/views/personal/edit.password'),
                        meta: {
                            title: '修改密码'
                        }
                    }
                ]
            },
            {
                path: 'reload',
                name: 'reload',
                component: () => import('@/views/reload')
            }
        ]
    }
]

// 当 children 不为空的主导航只有一项时，则隐藏
export const asyncRoutes = [
    /*{
        meta: {
            path: '/component',
            title: '组件',
            icon: 'sidebar-default'
        },
        children: [
            MultilevelMenuExample,
            BreadcrumbExample,
            KeepAliveExample,
            ComponentBasicExample,
            ComponentExtendExample,
            PermissionExample,
            MockExample,
            ExTernalLinkExample
        ]
    }*/
]

const lastRoute = [{
    path: '*',
    component: () => import('@/views/error/404.vue'),
    meta: {
        title: '404',
        sidebar: false
    }
}]

const router = new VueRouter({
    routes: constantRoutes
})

/**
 * 格式化树形结构数据生成 Vue-router 层级路由表
 */
export const generator = (routerMap, parent) => {
    return routerMap.map(item => {
        const {title, show, hideChildren, hiddenHeaderContent, hidden, icon, noCache} = item.meta || {}

        if (item.component) {
            if (item.component === 'Layout') {
                item.component = 'RouteView'
            } else if (item.component === 'ParentView') {
                item.component = 'RouteView'
                item.path = '/' + item.path
            }
        }

        const currentRouter = {
            path: item.path || `${parent && parent.path || ''}/${item.path}`,
            name: item.name || item.key || '',
            component: (() => import(`@/views/${item.component}`)),
            hidden: item.hidden,
            meta: {
                title: title,
                icon: allIcon[icon + 'Icon'] || icon,
                iconStr: icon === null ? 'profile' : icon,
                hiddenHeaderContent: hiddenHeaderContent,
                target: item.target,
                permission: item.name,
                keepAlive: noCache,
                hidden: hidden,
                remark: item.meta.remark
            },
            redirect: item.redirect
        }
        if (show === false) {
            currentRouter.hidden = true
        }
        if (!constantRouterComponents[item.component || item.key]) {
            currentRouter.path = `${parent && parent.path || ''}/${item.path}`
        }
        if (hideChildren) {
            currentRouter.hideChildrenInMenu = true
        }
        if (item.children && item.children.length > 0) {
            currentRouter.children = generator(item.children, currentRouter)
        }
        return currentRouter
    })
}

// 解决路由在 push/replace 了相同地址报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}

router.beforeEach(async (to, from, next) => {
    store.state.settings.enableProgress && NProgress.start()
    // 已经登录，但还没根据权限动态挂载路由
    if (store.getters['user/isLogin'] && !store.state.menu.isGenerate) {
        /**
         * 重置 matcher
         * https://blog.csdn.net/baidu_28647571/article/details/101711682
         */
        store.dispatch('permission/GenerateRoutes').then(async accessRoutes => {
            router.matcher = new VueRouter({
                routes: constantRoutes
            }).matcher
            accessRoutes = accessRoutes.filter(router => router.name !== 'Http://ruoyi.vip')
            const newAccessRoutes = await store.dispatch('menu/generateRoutes', {
                asyncRoutes,
                currentPath: to.path,
                accessRoutes
            })
            newAccessRoutes.push(...lastRoute)
            newAccessRoutes.forEach(route => {
                router.addRoute(route)
            })
            next({...to, replace: true})
        })
    }
    if (store.state.menu.isGenerate) {
        store.commit('menu/setHeaderActived', to.path)
    }
    to.meta.title && store.commit('settings/setTitle', to.meta.title)
    if (store.getters['user/isLogin']) {
        if (to.name) {
            if (to.matched.length !== 0) {
                // 如果已登录状态下，进入登录页会强制跳转到控制台页面
                if (to.name === 'login') {
                    next({
                        name: 'dashboard',
                        replace: true
                    })
                } else {
                    if (store.getters['user/roles'].length === 0) {
                        isRelogin.show = true
                        // 判断当前用户是否已拉取完user_info信息
                        store.dispatch('user/GetInfo').then(() => {
                            isRelogin.show = false
                            store.dispatch('permission/GenerateRoutes').then(async accessRoutes => {
                                console.log(accessRoutes, 'accessRoutes')
                                accessRoutes = accessRoutes.filter(router => router.name !== 'Http://ruoyi.vip')
                                const newAccessRoutes = await store.dispatch('menu/generateRoutes', {
                                    asyncRoutes,
                                    currentPath: to.path,
                                    accessRoutes
                                })
                                console.log(777, newAccessRoutes)
                                newAccessRoutes.push(...lastRoute)
                                newAccessRoutes.forEach(route => {
                                    router.addRoute(route)
                                })
                                next({...to, replace: true}) // hack方法 确保addRoutes已完成
                            })
                        }).catch(err => {
                            store.dispatch('user/LogOut').then(() => {
                                Message.error(err)
                                next({path: '/'})
                            })
                        })
                    }
                    if (!store.state.settings.enableDashboard && to.name === 'dashboard') {
                        // 如果未开启控制台页面，则默认进入侧边栏导航第一个模块，但如果侧边栏导航没有模块，则还是进入控制台页面
                        if (store.getters['menu/sidebarRoutes'].length > 0) {
                            const sidebarRoutes = store.getters['menu/sidebarRoutes']
                            next({
                                name: sidebarRoutes[0].name,
                                replace: true
                            })
                        }
                    }
                }
            } else {
                // 如果是通过 name 跳转，并且 name 对应的路由没有权限时，需要做这步处理，手动指向到 404 页面
                next({
                    path: '/404'
                })
            }
        }
    } else {
        if (to.name !== 'login') {
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    next()
})

router.afterEach(() => {
    store.state.settings.enableProgress && NProgress.done()
})

export default router
